/**
 * 该文件是用来操作登录、注册、获取用户信息、token 等操作，
 * 📢🔈📣几乎全部需要重写，不分析了 ❗❗❗
 */

import { defineStore } from 'pinia'

// 导入操作 Token 的方法
import { getToken, removeToken, setToken } from '../utils/token-utils'
import type { IUserinfo, UserInfoState } from './interface'
import { ElMessage } from 'element-plus'
import { staticRoutes, allAsyncRoutes } from '@/router/routes'
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore('userInfo', {
  state: (): UserInfoState => ({
    token: getToken() as string,
    menuRoutes: [...staticRoutes, ...allAsyncRoutes],
    userInfo: {} as IUserinfo
  }),

  actions: {
    // 登录
    async login(username: string, password: string) {
      // 调用登录接口api
      const res = await reqLogin(username, password)
      if (res.code === 20000) {
        // 将token存储在本地
        setToken(res.data.token)
        // 将token存放在state中
        this.token = res.data.token
        Promise.resolve(true)
      } else {
        Promise.reject(false)
      }
    },

    // 获取用户信息
    async getInfo() {
      const res = await reqUserInfo()
      if (res.code === 20000) {
        this.userInfo = res.data
        Promise.resolve(true)
      } else {
        Promise.reject(false)
      }
    },

    // 退出功能
    async reset() {
      // 调用api
      const res = await reqLogout()
      // 清除token
      if (res.code === 20000) {
        this.token = ''
        removeToken()
      }
      // 清除用户信息
      this.userInfo = {} as IUserinfo
    }
  }
})
